from storehouse.forms import OrderForm
from django.template.context import RequestContext
from django.shortcuts import render_to_response
from django import forms
from storehouse.models import order
from storehouse.models import *
from storehouse.forms import *
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required, permission_required
from storehouse.models import order
from storehouse.models import order_product
from storehouse.decorators import group_required
from django.contrib.auth.models import User, Group

from storehouse.models import inventory,inventory_product_diff
from django.db.models import Q 
import sys


def main_page(request):
    """
    main page of project
    """
    if   request.user.is_authenticated():
        pass
    else:
        return HttpResponseRedirect('/login')
    return render_to_response('main.html')

def logout_page(request):
    auth.logout(request)
    return HttpResponseRedirect('/')

@login_required
def error_view(request):
    Error_message = None
    if request.GET.has_key('error_message'):
        Error_message = request.GET['error_message']
    variables = RequestContext(request,{'error_message':Error_message})
    return render_to_response('error_view.html',variables)

@login_required
def address_view(request,address_id):
    print address_id
    address_show = None
    if request.user.has_perm(u'storehouse.addres_read'):
        try:
            address_show = address.objects.get(id = address_id)
        except:
            print "address_view", sys.exc_info()
    
    variables = RequestContext(request,{'address':address_show})
    return render_to_response('address_view.html',variables)
        
        
@permission_required(u'storehouse.document can view')
def document_view(request):
    document_o = None
    person_show = None
    document_show = None
    try:
        if request.method == 'POST':
           if request.POST.has_key('_print'):
              
               return HttpResponseRedirect("/admin/storehouse/print_document/%s" %request.POST['_print'])
        elif request.GET.has_key('document_id'):
            
            document_o = document.objects.get(id = request.GET['document_id'])
            
            if request.user.is_superuser:
                document_show = document_o
                person_show = person.objects.get(user = document_o.creator)
            elif request.user.has_perm(u'storehouse.StoMan'):
                person_o =  person.objects.get(user = user.objects.get(user_ptr = request.user).id)
                if document_o.storehouse == storehouse.objects.get(manager = person_o):
                    document_show = document_o
                    person_show = person_o
            else:
                user_o = user.objects.get(user_ptr = request.user)
                if user_o == document_o.creator:
                    document_show = document_o
                    person_show = person_o
                
                
    except:
         print "EXCEPTION", sys.exc_info()[1]
    variables = RequestContext(request,{'document':document_show,'person_creator':person_show})
    return render_to_response('document_view.html',variables)

from document_factory import DocumentFactory

def handle_PZ(doc):
    template = 'document_templates/PZ.xlsx'
    out = 'temp/PZ_out.xlsx'.format(doc.id)
    items = order_product.objects.filter(order=doc.order)
    elements = []
    for item in items:
        elements.append({'title': item.product.name, 'count': item.quantity, 'remarks': item.barcode})
    DocumentFactory.RenderFile(template, out, {
        'id': 1,
        'elements': elements,
    })
    return out, 'PZ.xlsx'

def handle_WZ(doc):
    template = 'templates/doc/WZ.xlsx'

@permission_required(u'storehouse.document can view')
def print_document(req, document_id):
    """ View function for printing a document """

    templatefile = 'document_print.html'

    doc = document.objects.get(id=document_id)

    symbol_handlers = {
        'PZ': handle_PZ,
        'WZ': handle_WZ,
    }

    sym = doc.document_type.symbol
    if sym not in symbol_handlers:
        return render_to_response(templatefile, {})

    filename, download_name = symbol_handlers[sym](doc)

    from django.core.servers.basehttp import FileWrapper
    from django.http import HttpResponse
    import os.path
    import mimetypes
    mimetypes.init()
    wrapper = FileWrapper(open(filename)) # I know this is very dirty...
    response = HttpResponse(wrapper, content_type=mimetypes.guess_type(filename)[0])
    response['Content-Length'] = os.path.getsize(filename)
    response['Content-Disposition'] = 'attachment; filename={0}'.format(download_name)
    return response

from storehouse.relationCheckers import getUserStorehouses
@permission_required(u'storehouse.liquidation can view')
def liquidation_view(request):
    liquidation_show = None
    try:
        if request.GET.has_key('liquidation_id'):
            liquidation_o = liquidation.objects.get(id = request.GET['liquidation_id'])
            liquidation_document_o = document.objects.get(liquidation = liquidation_o)
            person_storehouses = getUserStorehouses(request.user)
            if liquidation_document_o.storehouse in person_storehouses:
                liquidation_show = liquidation_o
            
    except:
       print "EXCEPTION", sys.exc_info()
    
    variables = RequestContext(request,{'liquidation':liquidation_show})
    return render_to_response('liquidation_view.html',variables)

@group_required('Managerowie Magazynow')
def inventory_applied(request):
    inventory_o = None
    inventory_show = None
    inventory_diffs = []
    try:
        if request.GET.has_key('inventory_id'):
            inventory_id = request.GET['inventory_id']
            storehouse_staff = False 
            inventory_o = inventory.objects.get(id = inventory_id )
            
            inventory_document =  document.objects.get(inventory  = inventory_o)
            user_storehouse = getUserStorehouses(request.user)
            storehouse_staff = (inventory_document.storehouse in user_storehouse)
            if storehouse_staff:
                inventory_show = inventory_o
                inventory_diffs = inventory_product_diff.objects.filter(inventory = inventory_o)
            
    except:
        print sys.exc_info()
    
    variables = RequestContext(request,{'inventory':inventory_show,'inventory_diffs':inventory_diffs})
    return render_to_response('inventory.html',variables)
    
    

@group_required('Magazynierzy','Managerowie Magazynow','Logistycy','Nadzorcy Logistykow')
def view_order(request):
    order_o  = None
    order_show = None
    related_products_o = []
    try:
        if request.GET.has_key('order_id'):
            order_id = request.GET['order_id']
            auser = request.user
            try:
                order_o  = order.objects.get(id= order_id)
            except:
                raise
            # Storehouse
            storehouse_staff = False 
            try:
                user_storehouses = getUserStorehouses(request.user)
                storehouse_staff = (order_o.storehouse_from in user_storehouses) or (order_o.storehouse_to in user_storehouses)
            except:
                pass
            #logistic supervisor
            print "role checking"
            if storehouse_staff:
                order_show = order_o
                related_products_o = order_product.objects.filter(order = order_show)
            elif auser == order_o.system_user:
                order_show = order_o
                related_products_o = order_product.objects.filter(order = order_show)
            elif Group.objects.get(name = 'Nadzorcy Logistykow') in auser.groups.all():
                order_show = order_o
                related_products_o = order_product.objects.filter(order = order_show)
        else:
            pass
    except:
        print "view_order",sys.exc_info()
        pass    
    variables = RequestContext(request,{'order':order_show,'order_products':related_products_o})
    return render_to_response('order_view.html',variables)

def f_callback(field, **kwargs):
    if field.name == "status":
        return MyStatusField(**kwargs)
    else:
        return field.formfield(**kwargs)

def test_page(request):
    form_obj = None
    if request.method == 'POST':
        pass
    elif request.GET.has_key('address_id'):
        pass
    else:
        pass
    form_obj = OrderForm()
    
    variables = RequestContext( request, {'form':form_obj})

    return render_to_response('logowanie.html', variables )
